
//
// 120322 - AH - (Midtun) Created.
// 120626 - AH - (Huset) Took ACCOUNT_ID in use.
// 120727 - AH - (Midtun *) Responds with array not list as used to.
// 120828 - AH - (Zen) Now serialize new ConversationElementsSerializable.
// 120828 - AH - (Huset) Did not return after reporting account not found, 
//               caused a NullPointerException.
//

package org.soekrat.server.servlets.ce;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.Account;
import org.soekrat.server.io.db.ConversationElement;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.serialization.ConversationElementSerializable;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements request to get
 *   {@link ConversationElement} given an
 *   {@link Account}.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class GetConversationElementsHttpServlet
  extends AbstractSoekratHttpServlet
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public GetConversationElementsHttpServlet(){}

  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    {
      if (!validate(res, def, req)) return;
      
      long akey=def.fetch(ACCOUNT_ID.name(), req).getLongValue();
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      Account owner=dao.getAccount(akey);
      if (owner==null)
      {
        respond(res, "Could not find account for key: "+akey);
        return;
      }
            
      List<ConversationElement> coes=dao.getConversationElements(owner);
         
      List<ConversationElementSerializable> l=
        new ArrayList<ConversationElementSerializable>();
      
      for (ConversationElement curr : coes) 
      {
        l.add(new ConversationElementSerializable(curr));
      }
        
      respond(res, l.toArray(ConversationElementSerializable.EMPTY_ARRAY));
    }
  }
  
  @Override
  public HttpRequestDef getHttpRequestDef()
  {
    HttpRequestDef retVal=new HttpRequestDef("/soekrat_server/get_ces")
      .desc("Get Conversation Elements").parameter(ACCOUNT_ID);
    return retVal;
  }
  
}
